package com.rongji.dfish.demo.editor.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rongji.dfish.demo.editor.service.uiadaptor.AdaptorManager;
import com.rongji.dfish.demo.editor.service.uiadaptor.ComponentInfo;
import com.rongji.dfish.demo.editor.service.uiadaptor.ComponentRelation;
import com.rongji.dfish.demo.editor.service.uiadaptor.ComponentRelation.Information;
import com.rongji.dfish.demo.editor.service.uiadaptor.ComponentTypeAdaptor;
import com.rongji.dfish.demo.editor.service.uiadaptor.PropertyDefine;
import com.rongji.dfish.demo.editor.service.uiadaptor.TypeAdaptor;
import com.rongji.dfish.ui.Widget;
import com.rongji.dfish.ui.command.DialogCommand;
import com.rongji.dfish.ui.form.Checkboxgroup;
import com.rongji.dfish.ui.helper.FormPanel;
import com.rongji.dfish.ui.helper.GridPanel;
import com.rongji.dfish.ui.helper.Label;
import com.rongji.dfish.ui.json.JsonWrapper;
import com.rongji.dfish.ui.layout.ButtonBar;
import com.rongji.dfish.ui.layout.FrameLayout;
import com.rongji.dfish.ui.layout.GridLayout;
import com.rongji.dfish.ui.layout.HorizontalLayout;
import com.rongji.dfish.ui.layout.VerticalLayout;
import com.rongji.dfish.ui.layout.View;
import com.rongji.dfish.ui.layout.grid.GridColumn;
import com.rongji.dfish.ui.layout.grid.Td;
import com.rongji.dfish.ui.layout.grid.Thead;
import com.rongji.dfish.ui.layout.grid.Tr;
import com.rongji.dfish.ui.widget.Button;
import com.rongji.dfish.ui.widget.Toggle;

@Controller
@RequestMapping("/components")
public class ComponentsController {
	AdaptorManager manager=AdaptorManager.getInstance();
	ComponentInfo com;
	HashMap<String, List<String[]>> special;
	@RequestMapping(value = "/index")
	@ResponseBody
	public Object index() throws Exception {
		View view=new View();
		GridLayout root=new GridLayout("root");
		view.setNode(root);
		root.setScroll(true).setFace(GridLayout.FACE_LINE).setPub(new Tr().setHeight("32")).setHoverable(true);
		
		Thead thead=new Thead();
		root.setThead(thead);
		thead.setCls("bg-form");
		Tr headRow=new Tr();
		thead.add(headRow);
		
		headRow.setData("name", "名字");
		headRow.setData("cname", "中文名");
		headRow.setData("isWrapper", "封装类");
		headRow.setData("oper", "更多");
		
		root.addColumn(GridColumn.text("padding", "18"));
		root.addColumn(GridColumn.text("name", "150"));
		root.addColumn(GridColumn.text("cname", "*"));
		root.addColumn(GridColumn.text("isWrapper", "60").setFormat("javascript:var d= this.x.data.isWrapper;if('1'==d){return \"<span style='color:gray'>封装类</span>\"};return '';"));
		root.addColumn(GridColumn.text("oper", "60").setFormat("[<a class='a-blue' href='javascript:;' onclick=\"VM(this).cmd('showComp','$name')\">查看</a>]").setAlign(GridColumn.ALIGN_CENTER));
		
		ComponentInfo compInfo=AdaptorManager.getInstance().getCompInfo();
		List<String> types=compInfo.getAllTypes();
		LinkedHashMap<String,List<String>>cateGroup=new LinkedHashMap<String,List<String>>();
		for(String type:types){
			String cate=compInfo.getCategory(type);
			List<String> cates=cateGroup.get(cate);
			if(cates==null){
				cates=new ArrayList<String>();
				cateGroup.put(cate, cates);
			}
			cates.add(type);
		}
	
		List<String> cates=new ArrayList<String>(cateGroup.keySet());
		compInfo.sortCategory(cates);
		for(String cate:cates){
			List<String> catetypes=cateGroup.get(cate);
			Tr group=new Tr();
			root.add(group);
			String cateLabel=compInfo.getCategoryName(cate)+"("+cate+") - "+catetypes.size();
			group.setData("padding", new Td().setColspan(5).setNode(new Toggle().setText(cateLabel).setHr(false).setOpen(true))
					.setStyle("font-weight:bold;color:#696;cursor:pointer").setValign("bottom"));
			group.setHeight("42");
			
			for(String type:catetypes){
				Tr data=new Tr();
				root.add(data);
				data.setData("name", type);
				data.setData("cname", compInfo.getTypeName(type));
				TypeAdaptor ta= compInfo.getAdaptor(type);
				if(ta instanceof ComponentTypeAdaptor){
					Class<?> clz=((ComponentTypeAdaptor) ta).getClz();
					if(JsonWrapper.class.isAssignableFrom(clz)){
						data.setData("isWrapper", "1");
					}
				}
			}
		}
		view.addCommand("showComp", new DialogCommand().setSrc("components/$0").setTemplate("std").setTitle("查看组件信息")
				.setHeight(DialogCommand.HEIGHT_LARGE).setWidth(DialogCommand.WIDTH_LARGE).setCover(true));
		return view;
	}
	@RequestMapping(value = "/{type}")
	@ResponseBody
	public Object showComp(@PathVariable String type) throws Exception {
		View view=new View();
		VerticalLayout vp=new VerticalLayout("root");
		view.setNode(vp);
//		vp.add(new Html(null,type));
		VerticalLayout shell2=new VerticalLayout("shell");
		vp.add(shell2,"*");
//		shell2.setStyle("margin:6px;").setCls("bd-mod").setHmin(14).setWmin(14);
		
		Widget<?> form=getCompFormPanel(type); 
		Widget<?> grid=getPropsGridPanel(type); 
		Widget<?> subs=getSubsGridPanel(type); 
		ButtonBar tabHead=new ButtonBar("main_bar");
		shell2.add(tabHead,"40");
		tabHead.setCls("modtabbar f-14").setFocusable(true).setPub(new Button(null).setCls("modtab"));
		//添加按钮
		tabHead.add(new Button(null,"    组件信息    ",null).setTarget(form.getId()).setFocus(true));
		tabHead.add(new Button(null,"    属性信息    ",null).setTarget(grid.getId()));
		tabHead.add(new Button(null,"    允许添加    ",null).setTarget(subs.getId()));
		
		HorizontalLayout shell3=new HorizontalLayout(null);
		shell2.add(shell3);
		
		FrameLayout film =new FrameLayout("main_film");
		shell3.add(film);
		film.setDft(form.getId());
		film.add(form);
		film.add(grid);
		film.add(subs);
		
		ButtonBar btnBar = new ButtonBar("btnBar");
		vp.add(btnBar, "50");
		btnBar.setPub(new Button(null).setCls("btn"));
		btnBar.setAlign(ButtonBar.ALIGN_RIGHT)
				.setCls("dlg-foot").setSpace(8).setStyle("padding-right:20px")
				.setWmin(20).setHmin(1);
		btnBar.add(new Button("取消").setOn(Button.EVENT_CLICK, "$.close(this);"));
		return view;	
	}
	private Widget<?> getSubsGridPanel(String type) {
		GridPanel fp=new GridPanel("subinfo");
		fp.setFace(GridPanel.FACE_LINE).setScroll(true).setPub(new Tr().setHeight("32"));

		List<String[]> show=new ArrayList<String[]>();
		ComponentRelation compRel=AdaptorManager.getInstance().getCompRelation();
		Map<String, List<Information>> spes=compRel.getSpecialParts(type);
		Map<String, List<Information>> other=compRel.getOtherType(type);
		List<Information> coms=compRel.getAcceptType(type);
		if(spes!=null)
		for(Map.Entry<String, List<Information>>entry:spes.entrySet()){
			for(Information info:entry.getValue()){
				StringBuilder sbAppPorps=new StringBuilder();
				if(info.getAppendingProperies()!=null){
					for(PropertyDefine pd:info.getAppendingProperies()){
						sbAppPorps.append(pd.getName()).append(' ');
					}
				}
				show.add(new String[]{
						info.getSubType(),
						"&lt;"+entry.getKey()+"&gt;",
						info.isSingle()?"1":null,
						info.getAddMethod(),
						sbAppPorps.toString()
				});
			}
		}
		
		if(other!=null)
			for(Map.Entry<String, List<Information>>entry:other.entrySet()){
				for(Information info:entry.getValue()){
					StringBuilder sbAppPorps=new StringBuilder();
					if(info.getAppendingProperies()!=null){
						for(PropertyDefine pd:info.getAppendingProperies()){
							sbAppPorps.append(pd.getName()).append(' ');
						}
					}
					show.add(new String[]{
							info.getSubType(),
							"["+entry.getKey()+"]",
							info.isSingle()?"1":null,
							info.getAddMethod(),
							sbAppPorps.toString()
					});
				}
			}
		if(coms!=null){
			for(Information info:coms){
				StringBuilder sbAppPorps=new StringBuilder();
				if(info.getAppendingProperies()!=null){
					for(PropertyDefine pd:info.getAppendingProperies()){
						sbAppPorps.append(pd.getName()).append(' ');
					}
				}
				show.add(new String[]{
						info.getSubType(),
						null,
						info.isSingle()?"1":null,
						info.getAddMethod(),
						sbAppPorps.toString()
				});
			}
		}

		fp.setGridData(show);
		
		fp.addColumn(GridColumn.text(0, "u","子节点","130"));
		fp.addColumn(GridColumn.text(1, "r","特殊关系","130").setFormat("javascript:var d= this.x.data.r;if(d){return d};return \"<span style='color:#CCC'>default</span>\";"));
		fp.addColumn(GridColumn.text(2, "s","唯一","80").setFormat("javascript:var d= this.x.data.s;if('1'==d){return \"<span style='color:gray'>唯一</span>\"};return '';"));
		fp.addColumn(GridColumn.text(3, "m","方法名","120"));
		fp.addColumn(GridColumn.text(4, "p","追加属性","*"));
		return fp;
	}
	private Widget<?> getPropsGridPanel(String type) {
		ComponentInfo compInfo=AdaptorManager.getInstance().getCompInfo();
		GridPanel fp=new GridPanel("propinfo");
		fp.setFace(GridPanel.FACE_LINE).setScroll(true).setPub(new Tr().setHeight("32"));
		TypeAdaptor ta= compInfo.getAdaptor(type);
		List<String[]> show=new ArrayList<String[]>();
		for(PropertyDefine def:ta.getDefineProps()){
			show.add(new String[]{
					def.getName(),
					compInfo.getPropName(def.getName(), type),
					def.getType(),
					def.getRequired()!=null&&def.getRequired()?"1":"0",
					def.getDefaultValue(),
					compInfo.getPropTip(def.getName(), type),
			});
		}
		fp.setGridData(show);
		fp.addColumn(GridColumn.text(1, "n","属性名","160"));
		fp.addColumn(GridColumn.text(2, "t","类型","80"));
		fp.addColumn(GridColumn.text(3, "r","必填","80").setFormat("javascript:var d= this.x.data.r;if('1'==d){return \"<span style='color:gray'>必填</span>\"};return '';"));
		fp.addColumn(GridColumn.text(4, "d","默认值","120"));
		fp.addColumn(GridColumn.text(5, "p","提示信息","*"));
		
		return fp;
	}
	
	private Widget<?> getCompFormPanel(String type) {
		ComponentInfo compInfo=AdaptorManager.getInstance().getCompInfo();
		FormPanel fp=new FormPanel("compinfo");
		fp.add(new Label("类型(type)",type));
		fp.add(new Label("名称",compInfo.getTypeName(type)));
		String cate=compInfo.getCategory(type);
		String cateLabel=compInfo.getCategoryName(cate)+"("+cate+")";
		fp.add(new Label("分组", cateLabel));
		TypeAdaptor ta=compInfo.getAdaptor(type);
		Class<?>clz=ta.getClass();
		if(ta instanceof ComponentTypeAdaptor){
			clz=((ComponentTypeAdaptor) ta).getClz();
		}
		List<String> value=new ArrayList<String>();
		if(JsonWrapper.class.isAssignableFrom(clz)){value.add("w");}
		if(compInfo.hasDataProp(type)){value.add("d");}
		if(compInfo.hasHiddensProp(type)){value.add("h");}
		if(compInfo.hasEventProp(type)){value.add("e");}
		List<String[]> options =Arrays.asList(new String[][]{
				{"w","封装类"},{"d","支持扩展属性"},{"h","支持隐藏提交"},{"e","支持动作事件"}});
		fp.add(new Checkboxgroup("feature","特性",value,options).setDisabled(true));
		String javaApiPath=clz.getName().replace('.', '/');
		fp.add(new Label("其他", "[<a href='api/java/"+javaApiPath+".html' target='_blanck'>查看API</a>]").setEscape(false));
		fp.getPrototype().setPub(new Tr().setHeight("40"));
		return fp;
	}



	
}
